package com.proxy.customer;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author: AaronChun
 * @create: 2019-03-25 10:53
 * @description:
 **/
public class CustomerDelegate implements CustomerInvocationHandler {

    //被代理对象
    private Object target;


    public Object getProxyInstance(Object target) {
        this.target = target;

        Class clazz = target.getClass();

        Object proxy = null;
        try {
            proxy = CustomerProxy.newProxyInstance(new CustomerClassLoader(clazz), clazz.getInterfaces(), this);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return proxy;

    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        try {

            System.out.println("start transaction.....");

            Object obj = method.invoke(target, args);

            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("transaction rollback");
        }finally {
            System.out.println("commit transaction.....");

        }


        return null;
    }
}
